package com.xinbochuang.machine.admin.controller.system;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinbochuang.machine.admin.domain.system.SysRole;
import com.xinbochuang.machine.admin.domain.system.SysUser;
import com.xinbochuang.machine.admin.service.system.ISysRoleService;
import com.xinbochuang.machine.admin.service.system.ISysUserService;
import com.xinbochuang.machine.common.constant.UserConstants;
import com.xinbochuang.machine.common.controller.BaseController;
import com.xinbochuang.machine.common.domain.LoginUser;
import com.xinbochuang.machine.common.domain.TableDataInfo;
import com.xinbochuang.machine.common.enums.UserStatus;
import com.xinbochuang.machine.common.utils.SecurityUtils;
import com.xinbochuang.machine.common.utils.ServletUtils;
import com.xinbochuang.machine.common.utils.StringUtils;
import com.xinbochuang.machine.framework.web.domain.AjaxResult;
import com.xinbochuang.machine.framework.web.service.TokenService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author 黄晓鹏
 * @date 2020-09-08
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private TokenService tokenService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/allList")
    public AjaxResult allList() {
        return AjaxResult.data(userService.list(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getDelFlag, 0)));
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Integer userId) {
        AjaxResult ajax = AjaxResult.ok();
        List<SysRole> roles = roleService.selectRoleAll();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        ajax.put("roles", SysUser.isAdmin(loginUser.getUser().getUserId()) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotNull(userId)) {
            ajax.put(AjaxResult.DATA_TAG, userService.getById(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @PostMapping
    public AjaxResult add(@RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUsername()))) {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，登录账号已存在");
        } else if (StrUtil.isNotBlank(user.getIdCard()) && UserConstants.NOT_UNIQUE.equals(userService.checkIdCardUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，身份证号码已存在");
        } else if (StrUtil.isNotBlank(user.getPhone()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，手机号码已存在");
        } else if (StrUtil.isNotBlank(user.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，邮箱账号已存在");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setCreateBy(SecurityUtils.getUsername());
        user.setCreateTime(DateUtil.now());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (StrUtil.isNotBlank(user.getIdCard()) && UserConstants.NOT_UNIQUE.equals(userService.checkIdCardUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，身份证号码已存在");
        } else if (StrUtil.isNotBlank(user.getPhone()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUsername() + "'失败，手机号码已存在");
        } else if (StrUtil.isNotBlank(user.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUsername() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(DateUtil.now());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Integer[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        //userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.updateById(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        return toAjax(userService.updateById(user));
    }
}

